package com.jt.blog.controller.AdminManage;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.blog.common.model.Page;
import com.jt.blog.common.model.Response;
import com.jt.blog.model.Blog;
import com.jt.blog.model.User;
import com.jt.blog.service.BlogReadService;
import com.jt.blog.service.BlogWriteService;
import com.jt.blog.service.UserService;
import com.jt.blog.vo.BlogQuery;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : 戴瑞
 * @Description : 用户管理模块
 * @create : 2018-03-26 22:33
 **/
@Controller
@RequestMapping("/back/admin")
public class AdminUserController {

    @Autowired
    private UserService userService;


    @RequestMapping("/userList")
    public String articleShow() {
        return "back/user/list";
    }

    @RequestMapping("/data/userList")
    @ResponseBody
    public Object getUserList(Integer offset, Integer limit, User user) {
        Map<String, Object> map = new HashMap<>();
        BlogQuery query = new BlogQuery();
        // 只查询博主公开的博客
        query.setPersonal(0);
        Page<User> page = new Page<>();
        page.setPageSize(limit);
        // 求当前页
        page.setPageNo((offset + limit) / limit);
        Response<Page<User>> response = userService.getAllUser(page, user);
        if (response.isSuccess()) {
            map.put("total", page.getTotal());
            map.put("rows", page.getRows());
        } else {
            return response;
        }
        return map;
    }

    @RequestMapping("/update/userstatus")
    @ResponseBody
    public Response<String> updateUserStatus(HttpServletRequest request) throws IOException {
        Response<String> response = new Response<>();
        String userList = request.getParameter("users");
        ObjectMapper mapper = new ObjectMapper();

        User[] users = mapper.readValue(userList, User[].class);
        if (ArrayUtils.isEmpty(users)) {
            response.setError("更新失败，请重试！");
        }
        userService.updateUserStatus(users);
        response.setResult("冻结此用户成功");

        return response;
    }

    @RequestMapping("/delete/user")
    @ResponseBody
    public Response<String> deleteUser(@RequestParam("ids") Long[] ids) {
        Response<String> response = new Response<>();
        if (ArrayUtils.isEmpty(ids)) {
            response.setError("错误！ID为空");
        } else {
            userService.deleteUser(ids);
            response.setResult("删除成功");
        }
        return response;
    }
}
